<?php

namespace app\api\service;

use app\common\BaseHelper;

use app\admin\model\Memberlevel as MemberlevelMdl;
use app\admin\model\Member;
use app\admin\model\Membercoupon;
use app\admin\model\Coupon;
use app\admin\model\Integralrecord;
use app\admin\model\Rechargerecord;
use app\admin\model\MessageNotice;
use app\api\service\Message as MessageService;

use think\Db;
use think\Exception;

class Memberlevel
{

    /**
     * 开通成功后更新会员相关信息
     */
    public static function updateMember($param){
        if (!$param) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        if (empty($param->memberId) || empty($param->levelId) || empty($param->vip_cost) || empty($param->vip_time) || empty($param->pay_method)) {
            return ['code' => 0, 'msg' => '参数错误'];
        }

        $model = new Member();
        Db::startTrans();
        try {
            $memberId = $param->memberId;

            // 是否开通的当前的会员等级
            $memberInfo = $model->where('id', $memberId)->field('member_level_id, level_time, level_open_time, level_end_time, c_id')->find();
            if ($memberInfo['member_level_id'] == $param->levelId) {
                // 时间累加
                $openTime = $memberInfo['level_open_time'];
                $levelTime = $memberInfo['level_time'] + ($param->vip_time * 30);
                $endTime = date('Y-m-d H:i:s', strtotime($openTime) + 3600 * 24 * $levelTime);
            } else {
                $openTime = date('Y-m-d H:i:s', time());
                $levelTime = $param->vip_time * 30; // 单位：天
                $endTime = date('Y-m-d H:i:s', strtotime($openTime) + 3600 * 24 * $levelTime);
            }
            $data = [
                'member_level_id' => $param->levelId,
                'level_time' => $levelTime,  // 单位：天
                'level_open_time' => $openTime,
                'level_end_time' => $endTime,
            ];

            $result = $model->allowField(true)->save($data, ['id' => $memberId]);

            if ($result !== false) {
                $memberlevelInfo = MemberlevelMdl::where('id', $param->levelId)->field('name, img_url, is_coupon, coupon_ids')->find();

                // 赠送优惠券
                if ($memberlevelInfo['is_coupon'] == 1) {
                    $couponIds = Coupon::where(['id' => ['in', $memberlevelInfo['coupon_ids']], 'coupon_purpose' => 1, 'end_time' => ['gt', date('Y-m-d H:i:s')]])->column('id');
                    $countCoupon = 0;
                    if ($couponIds) {
                        foreach ($couponIds as $couponId) {
                            // 用户是否已有该优惠券
                            $couponInfo = Membercoupon::where(['member_id' => $param->memberId, 'coupon_id' => $couponId])->find();
                            if ($couponInfo) {
                                continue;
                            }
                            $couponData = [
                                'id' => BaseHelper::getUUID(),
                                'create_date' => date('Y-m-d H:i:s'),
                                'member_id' => $param->memberId,
                                'coupon_id' => $couponId
                            ];

                            $couponRes = Membercoupon::insert($couponData);
                            if($couponRes === false){
                                Db::rollback();
                                return ['code' => 0, 'msg' => '赠送优惠券失败'];
                            }
                            $countCoupon ++;
                        }
                        if ($countCoupon) {
                            // 添加账户通知消息 -- 获得优惠券
                            $couponMesData = [
                                'create_date' => date('Y-m-d H:i:s'),
                                'member_id' => $param->memberId,
                                'img_url' => '',
                                'title' => '您获得了优惠券',
                                'detail' => '您获得了' . $countCoupon . '张优惠券，点击立即使用',
                                'type' => 1,
                            ];
                            $couponMesRes = MessageNotice::insert($couponMesData);
                            if($couponMesRes === false){
                                Db::rollback();
                                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加优惠券账户通知消息失败');
                            }

                            // 推送送APP消息
                            $mesData = [
                                'template_type' => 1,
                                'template_data' => [
                                    'transmission_type' => 1,
                                    'transmission_content' => '',
                                    'title' => '您获得了优惠券',
                                    'text' => '您获得了' . $countCoupon . '张优惠券，点击立即使用',
                                    'logo'  => '',
                                    'logo_url'  => '',
                                ],
                                'cid' => $memberInfo['c_id'], // 推送通知至指定用户时填写
                                'cid_list' => '', // 推送通知至指定用户列表时填写
                            ];
                            MessageService::pushNotice($mesData);
                        }
                    }
                }

                // 开通会员送积分
                $integralRule = db('integral_rule')->find();
                $integralRes = $model->where('id', $memberId)->setInc('integral', $integralRule['open_member']);
                if($integralRes === false){
                    Db::rollback();
                    return ['code' => 0, 'msg' => '开通会员送积分失败'];
                }

                // 添加积分记录
                $integralData = [
                    'create_date' => date('Y-m-d H:i:s'),
                    'order_no' => BaseHelper::getUUID(),
                    'integral_id' => '',
                    'coupon_id' => '',
                    'member_id' => $param->memberId,
                    'num' => 1,
                    'exchange_num' => $integralRule['open_member'],
                    'type' => 1,
                    'source' => '开通会员等级',
                ];
                $intRecordRes = Integralrecord::insert($integralData);
                if($intRecordRes === false){
                    Db::rollback();
                    return ['code' => 0, 'msg' => '添加积分记录失败'];
                }

                // 添加消费记录
                $recordData = [
                    'create_date' => date('Y-m-d H:i:s'),
                    'order_no' => create_order_sn(),
                    'member_id' => $param->memberId,
                    'record_money' => $param->vip_cost,
                    'type' => 2,
                    'detail' => '开通会员等级',
                    'pay_method' => $param->pay_method,
                    //'status' => 2
                    'status' => 1
                ];
                $recordRes = Rechargerecord::insert($recordData);
                if($recordRes === false){
                    Db::rollback();
                    return ['code' => 0, 'msg' => '添加消费记录失败'];
                }

                // 是否是余额支付
                if ($param->pay_method == 3) {
                    // 用户减余额
                    $memberRes = $model->where('id', $memberId)->setDec('balance', $param->vip_cost);
                    if($memberRes === false){
                        Db::rollback();
                        return ['code' => 0, 'msg' => '用户减余额失败'];
                    }

                    /*
                    // 添加账户通知消息 -- 钱包金额发生变化
                    $messageData = [
                        'create_date' => date('Y-m-d H:i:s'),
                        'member_id' => $param->memberId,
                        'img_url' => $memberlevelInfo['img_url'],
                        'title' => '您的钱包金额有了变化',
                        'detail' => '您花费了' . ($param->vip_cost / 100) . '元，开通了' . $memberlevelInfo['name'] . '，查看我的钱包',
                        'type' => 3
                    ];
                    $messageRes = MessageNotice::insert($messageData);
                    if($messageRes === false){
                        Db::rollback();
                        return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加余额账户通知消息失败');
                    }
                    */
                }

                Db::commit();
                return ['code' => 1, 'msg' => '开通成功'];
            } else {
                Db::rollback();
                return ['code' => 0, 'msg' => $model->getError()];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
}